import { getAll, saveOrUpdate, deleteMenu, getEditMenuInfo } from '@/api/menus'
import type { MenuItem, CreateOrEditMenu } from '@/api/menus'
import { ref, computed } from 'vue'
import router from '@/router/index'
import { ElMessage, ElMessageBox } from 'element-plus'
import 'element-plus/dist/index.css'


// 最外面包裹一层函数
export function useMenus() {

    //1.保存所有菜单数据
    const allMenus = ref([] as MenuItem[])

    //2.获取所有菜单数据的函数
    const getAllMenus = async () => {
        const { data } = await getAll()
        if (data.code === '000000') {
            allMenus.value = data.data
        } else {
            ElMessage.error('获取菜单失败')
            throw new Error('获取菜单失败')
        }
    }
    getAllMenus()

    // 3.顶级菜单筛选逻辑
    const topMenus = computed(() => allMenus.value.filter((menu) => menu.level === 0))

    // 4.表单的响应式数据
    const form = ref<CreateOrEditMenu>({
        name: '',
        href: '',
        parentId: -1,
        description: '',
        icon: '',
        shown: true,
        orderNum: 0
    })

    // 5.封装提交表单的事件处理
    const onSubmit = async () => {
        const { data } = await saveOrUpdate(form.value)
        //    console.log(res)
        if (data.code === '000000') {
            ElMessage.success('添加菜单成功')
            router.push({ name: 'menus' })
        } else {
            ElMessage.error('获取菜单失败')
            throw new Error('获取菜单失败')
        }

    }


    // 6.删除事件
    const handleDelete = async (id: number) => {
        await ElMessageBox.confirm('确定删除该菜单吗？', '重要提醒', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',

        }).catch(() => {
            ElMessage.info('已取消删除！')
            return new Promise(() => { console.log(id) })
        })
        const { data } = await deleteMenu(id)
        if (data.code === '000000' && data.data) {
            ElMessage.success('删除菜单成功')
            getAllMenus()
        } else {
            ElMessage.error('删除菜单失败')
            throw new Error('删除菜单失败')
        }
    }

    // 7.根据id获取菜单信息
    const getMenuInfoById = async (id: number) => {
        if (!Number(id)) {
            isCreate.value = true
            return  //拦截，是新增的话就不用编辑菜单信息了
        } else {
            isCreate.value = false
        }
        const { data } = await getEditMenuInfo(id)
        if (data.code === '000000') {
            form.value = data.data.menuInfo
        } else {
            ElMessage.error(`获取${id}菜单信息失败`)
            throw new Error(`获取${id}菜单信息失败`)
        }
    }

    
    //设置状态和文字
    const isCreate = ref(true)
    const msgText = computed(() => (isCreate.value ? '立即创建' : '立即更新'))

    return { allMenus, topMenus, getAllMenus, form, onSubmit, handleDelete, getMenuInfoById, msgText, isCreate }
}
